/*
 Copyright (C) 2010 Chris Hawkins. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 
 * Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 
 * Neither the name of the author nor the names of its contributors may be used
 to endorse or promote products derived from this software without specific
 prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "AsdUtil.h"
#import "AsdRequest.h"
#import <CommonCrypto/CommonHMAC.h>
#import "NSData+Base64.h"

@implementation ASDSpUtil
- (id)                  init {
    return nil;             // Static class - can not be instanced
}

+ (NSDateFormatter*)    awsGmtDateFormatter {
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat: @"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    [format setTimeZone: [NSTimeZone timeZoneForSecondsFromGMT: 0 ]];
    return [format autorelease];
}

+ (NSString*)           base64forData: (NSData*) data_ {
    // see http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
    return [data_ base64EncodedString];
}

+ (NSData*)             hmacSHA256withKey: (NSString*) key_ forString: (NSString*) string_ {
    NSData  *rawData = [[string_ dataUsingEncoding: NSUTF8StringEncoding] retain];
    NSData  *keyData = [[key_    dataUsingEncoding: NSUTF8StringEncoding] retain];
    
    uint8_t buffer[CC_SHA256_DIGEST_LENGTH]  = { 0 };
    
    CCHmacContext  context;
    CCHmacInit(   &context, kCCHmacAlgSHA256, keyData.bytes, keyData.length );
    CCHmacUpdate( &context,                   rawData.bytes, rawData.length );
    CCHmacFinal(  &context, buffer );
    
    [rawData release];
    [keyData release];
    return [NSData dataWithBytes: buffer length: sizeof( buffer )];
}
+ (NSString*)           urlEncode: (NSString*)  baseString_ {
    // see http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/
    //         (CFStringRef)@"!*'();:@&=+$,/?%#[]",
    NSString *encodedString = (NSString*) CFURLCreateStringByAddingPercentEscapes( NULL,
                                                                                   (CFStringRef) baseString_,
                                                                                   NULL,
                                                                                   (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                   kCFStringEncodingUTF8);
    return [encodedString autorelease];
}
#pragma mark -- logging
+ (void)                logHttpResponseForRequest: (ASDRqBase*) request_ {
    NSHTTPURLResponse   *httpResponse = [request_ httpResponse];
    [httpResponse retain];
    if ( httpResponse != nil ) {
        NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity: 400];
        [buffer appendFormat:@"Request# %u HTTP status: %u",[request_ sequenceNumber],[httpResponse statusCode]];
        NSArray *keys = [[[httpResponse allHeaderFields] allKeys] retain];
        for ( NSString *key in keys ) {
            NSString *value = [[httpResponse allHeaderFields] valueForKey: key];
            [buffer appendFormat: @"\n %@=%@", key, value];
        }
        [keys release];
        NSLog( @"%@", buffer );
        [buffer release];
    }
    [httpResponse release];
}
+ (void)                logUrlRequestForRequest:   (ASDRqBase*) request_ {
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity: 400];
    [buffer appendFormat:@"Request# %u URL: ",[request_ sequenceNumber]];
    if ( request_.urlRequest != nil ) {
        [buffer appendString: [[request_.urlRequest URL] absoluteString]];
    } else {
        [buffer appendString: @"??"];
    }
    NSLog( @"%@", buffer );
    [buffer release];
    
}

@end
